<?php
/**
 * 静态 function
 */
class framework_static_function {
    private static $numLength = 14;
    /**
     * 远程获取文件
     */
    public static function curl_file_get_contents($durl) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, trim($durl));
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        // curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
        curl_setopt($ch, CURLOPT_REFERER, _REFERER_);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        // print_r(curl_getinfo($ch));exit;
        // var_dump(curl_error($ch));
        curl_close($ch);
        // var_dump($data);
        // exit;
        return $data;
    }

    /**
     * @param $url
     * @param $para
     * @param string $method
     * @return mixed
     */
    public static function http_curl($url, $para, $method = "POST") {
        $data_string = http_build_query($para);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($method == "POST") {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        } else {
            //get
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        return $result;
    }

    public static function https_curl($url, $para, $cert = null) {
        if (strpos($url, 'PATr0003') === false) {
            static_function::write_log($url . "\t" . $para, 'rlms_interface');
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);

        //测试数据
        curl_setopt($ch, CURLOPT_POSTFIELDS, $para);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($cert == null) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        } else {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); ;
            curl_setopt($ch, CURLOPT_CAINFO, $cert);
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type:application/json',
            'Content-Length: ' . strlen($para)
        ));
        $result = curl_exec($ch);
        curl_close($ch);
        if (!empty($result)) {
            return json_decode($result, true);
        } else {
            return false;
        }
    }

    /**
     * 获取page URL
     */
    public static function curPageURL() {
        if (SERVER_GET_IP)
            $_SERVER["SERVER_NAME"] = isset($_SERVER["SERVER_ADDR"]) ? $_SERVER["SERVER_ADDR"] : $_SERVER["SERVER_NAME"];
        $pageURL = 'http';

        if (isset($_SERVER["HTTPS"])) {
            if ($_SERVER["HTTPS"] == "on")
                $pageURL .= "s";
        }
        $pageURL .= "://";

        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }

    /**
     * 获取 URL
     */
    public static function curURL() {
        $pageURLArr = explode("/", self::curPageURL());
        unset($pageURLArr[count($pageURLArr) - 1]);
        return implode("/", $pageURLArr) . "/";
    }

    public static function microtime_float() {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }

    /**
     * 检查文件夹
     */
    public static function mkdirs($path, $mode = 0777) {
        $dirs = explode('/', $path);
        $pos = strrpos($path, ".");
        if ($pos === false) {
            // note: three equal signs
            // not found, means path ends in a dir not file
            $subamount = 0;
        } else {
            $subamount = 1;
        }

        for ($c = 0; $c < count($dirs) - $subamount; $c++) {
            $thispath = "";
            for ($cc = 0; $cc <= $c; $cc++) {
                $thispath .= $dirs[$cc] . '/';
            }
            // echo $thispath . "<br />";
            if (!file_exists($thispath)) {
                //print "$thispath<br>";
                mkdir($thispath, $mode);
            }
        }
    }

    /**
     * @param $array
     * @param int $num
     * @param bool $jsonHeader
     * 输出标准json
     *
     * @access  public
     *
     * @author  jonah.fu
     * @date    2012-04-19
     *
     * @return   string
     *
     */
    public static function output_json($array, $num = true, $jsonHeader = true) {
        header("Expires: Mon, 26 Jul 1970 01:00:00 GMT");
        $jsonHeader && header('Content-type: application/json;charset=utf-8');
        header("Pramga: no-cache");
        header("Cache-Control: no-cache");
        if ($num) {
            exit(json_encode((array)($array), JSON_NUMERIC_CHECK));
        } else {
            exit(json_encode((array)($array)));
        }
    }
    /**
     * @param $array
     * @param int $num
     * @param bool $jsonHeader
     * 输出标准jsonp
     *
     * @access  public
     *
     * @author  jonah.fu
     * @date    2012-04-19
     *
     * @return   string
     *
     */
	public static function output_jsonp($array,$callback='callback',$num = true, $jsonHeader = true) {
    	header("Expires: Mon, 26 Jul 1970 01:00:00 GMT");
    	$jsonHeader && header('Content-type: application/json;charset=utf-8');
    	header("Pramga: no-cache");
    	header("Cache-Control: no-cache");
    	if ($num) {
    		exit($callback.'('.json_encode((array)($array), JSON_NUMERIC_CHECK).');');
    	} else {
    		exit($callback.'('.json_encode((array)($array)).');');
    	}
    }
    

    /**
     * 魔术引号
     */
    public static function strip_array($var) {
        return is_array($var) ? array_map("self::strip_array", $var) : addslashes(htmlspecialchars($var));
    }

    /**
     * 圆周计算
     *
     */
    public static function rad($d) {
        return bcmul($d, (bcdiv('3.1415926535898', '180', self::$numLength)), self::$numLength);
    }

    /**
     * 经纬度之间获取距离
     */
    public static function GetDistance($lat1, $lng1, $lat2, $lng2) {
        $EARTH_RADIUS = 6378.137;
        $radLat1 = self::rad($lat1);
        //echo $radLat1;
        $radLat2 = self::rad($lat2);
        $a = bcsub($radLat1, $radLat2, self::$numLength);
        $b = bcsub(self::rad($lng1), self::rad($lng2), self::$numLength);
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $s = bcmul($s, $EARTH_RADIUS, self::$numLength);
        $s = round($s * 10000) / 10000;
        return $s;
    }

    public static function debug($var) {
        if ($_COOKIE['debug'] == 'jkdc') {
            print_r('<pre style="text-align: left">');
            print_r((array)$var);
            print_r('</pre>');
        }
    }

    public static function write_log($logs, $file_name = '') {
        $logs = date('Y-m-d H:i:s') . "\t" . $logs . "\r\n";
        if (empty($file_name)) {
            $file = APP_PATH . '/../logs/' . date("Y/m/d") . '/sites.txt';
        } else {
            $file = APP_PATH . '/../logs/' . date("Y/m/d") . '/' . $file_name . '.txt';
        }

        if (!file_exists(dirname($file))) {
            mkdir(dirname($file), 0775, true);
        }
        error_log($logs, 3, $file);
    }

    public static function history_back($msg = '') {
        if ($msg) {
            $msg = "alert('" . $msg . "');";
        }
        echo "<script>" . $msg . "history.back(-1);</script>";
        die ;
    }

    public static function rand_money() {
        return mt_rand(1, 9) / 100;
    }

    //封装rlms请求数据成json格式
    public static function rlms_json($para) {
        $data_string = "{";
        foreach ($para as $key => $val) {
            $data_string .= $key . ":'" . $val . "',";
        }
        $data_string = substr($data_string, 0, -1);
        $data_string .= "}";
        return $data_string;
    }

    //短信通知开发
    public static function notice_developer($msg, $mobile = '') {
        $mobile = $mobile ? $mobile : DEVELOPER_MOBILE;
        static_message::send($mobile, $msg);
    }

    /**
     *
     */
    public static function set_cookie($key, $value, $time = '24*60*60') {
        setCookie($key, $value, $time, '/');
    }

    /**
     * 将ip转为整数
     */
    public static function ipton($ip){
        $ip_arr=explode('.',$ip);//分隔ip段
        foreach ($ip_arr as $value){
            $iphex=dechex($value);//将每段ip转换成16进制
            if(strlen($iphex)<2){//255的16进制表示是ff，所以每段ip的16进制长度不会超过2
                $iphex='0'.$iphex;//如果转换后的16进制数长度小于2，在其前面加一个0
            //没有长度为2，且第一位是0的16进制表示，这是为了在将数字转换成ip时，好处理
            }
            $ipstr.=$iphex;//将四段IP的16进制数连接起来，得到一个16进制字符串，长度为8
        }
        return hexdec($ipstr);//将16进制字符串转换成10进制，得到ip的数字表示
    }

    /**
     * 将整数转为ip
     */
    public static function ntoip($n){
        $iphex=dechex($n);//将10进制数字转换成16进制
        $len=strlen($iphex);//得到16进制字符串的长度
        if(strlen($iphex)<8){
            $iphex='0'.$iphex;//如果长度小于8，在最前面加0
            $len=strlen($iphex); //重新得到16进制字符串的长度

            for($i=0,$j=0;$j<$len;$i=$i+1,$j=$j+2){//循环截取16进制字符串，每次截取2个长度
                $ippart=substr($iphex,$j,2);//得到每段IP所对应的16进制数
                $fipart=substr($ippart,0,1);//截取16进制数的第一位
                if($fipart=='0'){//如果第一位为0，说明原数只有1位
                    $ippart=substr($ippart,1,1);//将0截取掉
                }
                $ip[]=hexdec($ippart);//将每段16进制数转换成对应的10进制数，即IP各段的值
            }
            return implode('.', $ip);//连接各段，返回原IP值
        }
    }
    
    public static function refreshframe(){
        echo "<script>top.location.href = './index.php?act=admin&st=adminLogin'</script>";
    }


    /**
     * 提现、 充值发邮件调用
     */
    public static function sendMaill($address, $subject, $content, $username = '')
    {
        try {
            require_once(DIR_ROOT.'/framework/vendor/PHPMailer_5.2.2/class.phpmailer.php');
            $mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
            //$mail->IsSendmail(); // telling the class to use SendMail transport
            $mail->IsSMTP(); // telling the class to use SMTP

            $mail->SMTPDebug  = false;
            $mail->Debugoutput = "error_log";
            // 1 = errors and messages
            // 2 = messages only
            $mail->SMTPAuth   = true;                  // enable SMTP authentication
            //$mail->SMTPSecure = "ssl";

            $mail->Host       = MAIL_HOST; // sets the SMTP server
            $mail->Port       = 25;                    // set the SMTP port for the GMAIL server
            $mail->Username   = MAIL_USERNAME; // SMTP account username
            $mail->Password   = MAIL_PASSWORD;        // SMTP account password
            $mail->CharSet    = "UTF-8";
            // $mail->SetFrom('caipiaoadmin@douyole.com', '平安');
            $mail->SetFrom(MAIL_FROM, '平安');
            $mail->Subject = $subject;
            $mail->MsgHTML($content);
            if($address && is_array($address))
            {
                foreach ($address as $key => $value) {
                    if($value)
                    {
                        $mail->AddAddress($value, $username == '' ? $value : $username);
                    } 
                }
            }
            $info = $mail->Send();
            return $info;
        } catch (Exception $e) {
            //framework_static_function::write_log("邮件发送失败\t".$e->getMessage());
            $me = '系统发送邮件-';
            $admin = 0;
            $exc = $e->getMessage();
            if(isset($_SESSION['admin']['username'])){
                $me = '操作员'.$_SESSION['admin']['username'].'发送邮件-';
                $admin = $_SESSION['admin']['userid'];
            }
            $me .= $subject;
            if($address && is_array($address)){
                foreach ($address as $key => $value) {
                    if($value){
                        $username = $username == '' ? $value : $username;
                        $memo = $me.'-'.$value.'-'.$username.'失败,msg:'.$exc;
                        $adminLog = array(
                            'type' => '11',
                            'memo' => $memo,
                            'source_record' => '',
                            'target_record' => '',
                            'admin_id' => $admin
                        );
                        //mongodb记录日志：
                        model_mongodb::mgLog($adminLog,true);
                    } 
                }
            }
            return false;
        }
    }
}
?>